
// src/pages/ActiveWorkoutPage.tsx
import React, { useState, useEffect } from 'react';
import {
    IonPage, IonHeader, IonToolbar, IonTitle, IonContent,
    IonList, IonItem, IonLabel, IonInput, IonButton,
    IonIcon, IonProgressBar, IonDatetime
} from '@ionic/react';
import { play, pause, checkmark, close } from 'ionicons/icons';
import { useHistory, useParams } from 'react-router';
import { useAuth } from '../contexts/AuthContext';
import { startWorkout, completeWorkout } from '../services/workoutService';
import { WorkoutPlan } from '../models/WorkoutPlan';
import { WorkoutRecord,CompletedExercise, CompletedSet } from '../models/WorkoutRecord';

const ActiveWorkoutPage: React.FC = () => {
    const history = useHistory();
    const { planId } = useParams<{ planId: string }>();
    const { user } = useAuth();
    const [workoutRecord, setWorkoutRecord] = useState<WorkoutRecord | null>(null);
    const [workoutPlan, setWorkoutPlan] = useState<WorkoutPlan | null>(null);
    const [currentExerciseIndex, setCurrentExerciseIndex] = useState(0);
    const [currentSetIndex, setCurrentSetIndex] = useState(0);
    const [timer, setTimer] = useState(0);
    const [isPaused, setIsPaused] = useState(false);
    const [notes, setNotes] = useState('');

    useEffect(() => {
        const initializeWorkout = async () => {
            if (!user || !planId) return;

            try {
                // 获取计划详情
                // 在实际应用中，这里应该从API获取计划详情
                const plan: WorkoutPlan = {
                    id: planId,
                    userId: user.id,
                    name: "全身训练",
                    description: "全身力量训练计划",
                    exercises: [
                        { id: "1", name: "深蹲", sets: 3, reps: 10, weight: 60, restTime: 90 },
                        { id: "2", name: "卧推", sets: 3, reps: 8, weight: 50, restTime: 90 },
                        { id: "3", name: "划船", sets: 3, reps: 12, weight: 40, restTime: 60 },
                    ],
                    createdAt: new Date()
                };

                setWorkoutPlan(plan);

                // 开始锻炼记录
                const record = await startWorkout(planId, user.id);
                setWorkoutRecord({
                    ...record,
                    exercises: plan.exercises.map(ex => ({
                        id: ex.id,
                        name: ex.name,
                        sets: Array(ex.sets).fill(0).map((_, i) => ({
                            setNumber: i + 1,
                            reps: ex.reps,
                            weight: ex.weight
                        }))
                    }))
                });
            } catch (error) {
                console.error('开始锻炼失败:', error);
                history.push('/workout-plans');
            }
        };

        initializeWorkout();
    }, [user, planId, history]);

    useEffect(() => {
        let interval: NodeJS.Timeout | null = null;

        if (workoutRecord && !isPaused) {
            interval = setInterval(() => {
                setTimer(prev => prev + 1);
            }, 1000);
        }

        return () => {
            if (interval) clearInterval(interval);
        };
    }, [workoutRecord, isPaused]);

    const handleSetComplete = (reps: number, weight: number) => {
        if (!workoutRecord) return;

        const updatedExercises = [...workoutRecord.exercises];
        const currentExercise = updatedExercises[currentExerciseIndex];

        const updatedSets = [...currentExercise.sets];
        updatedSets[currentSetIndex] = {
            ...updatedSets[currentSetIndex],
            reps,
            weight
        };

        updatedExercises[currentExerciseIndex] = {
            ...currentExercise,
            sets: updatedSets
        };

        setWorkoutRecord({
            ...workoutRecord,
            exercises: updatedExercises
        });

        // 移动到下一组或下一个动作
        if (currentSetIndex < currentExercise.sets.length - 1) {
            setCurrentSetIndex(currentSetIndex + 1);
        } else if (currentExerciseIndex < workoutRecord.exercises.length - 1) {
            setCurrentExerciseIndex(currentExerciseIndex + 1);
            setCurrentSetIndex(0);
        } else {
            // 所有动作完成
            setIsPaused(true);
        }
    };

    const formatTime = (seconds: number) => {
        const mins = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    };

    const handleCompleteWorkout = async () => {
        if (!workoutRecord || !user) return;

        try {
            const completedRecord = {
                ...workoutRecord,
                endTime: new Date(),
                notes
            };

            await completeWorkout(completedRecord);
            history.push('/history');
        } catch (error) {
            console.error('完成锻炼失败:', error);
        }
    };

    if (!workoutRecord || !workoutPlan) {
        return (
            <IonPage>
                <IonHeader>
                    <IonToolbar>
                        <IonTitle>开始锻炼</IonTitle>
                    </IonToolbar>
                </IonHeader>
                <IonContent>
                    <p>加载中...</p>
                </IonContent>
            </IonPage>
        );
    }

    const currentExercise = workoutRecord.exercises[currentExerciseIndex];
    const currentSet = currentExercise.sets[currentSetIndex];

    return (
        <IonPage>
            <IonHeader>
                <IonToolbar>
                    <IonTitle>{workoutPlan.name}</IonTitle>
                </IonToolbar>
            </IonHeader>
            <IonContent className="ion-padding">
                <div style={{ textAlign: 'center', marginBottom: 20 }}>
                    <h2>{formatTime(timer)}</h2>
                    <IonButton onClick={() => setIsPaused(!isPaused)}>
                        <IonIcon slot="icon-only" icon={isPaused ? play : pause} />
                    </IonButton>
                </div>

                <IonProgressBar
                    value={(currentExerciseIndex + currentSetIndex / currentExercise.sets.length) / workoutRecord.exercises.length}
                />

                <div style={{ textAlign: 'center', margin: '20px 0' }}>
                    <h3>{currentExercise.name}</h3>
                    <p>组数: {currentSetIndex + 1} / {currentExercise.sets.length}</p>
                </div>

                <IonList>
                    <IonItem>
                        <IonLabel position="stacked">完成次数</IonLabel>
                        <IonInput
                            type="number"
                            value={currentSet.reps}
                            onIonChange={e => {
                                const reps = parseInt(e.detail.value!, 10);
                                handleSetComplete(reps, currentSet.weight);
                            }}
                        />
                    </IonItem>

                    <IonItem>
                        <IonLabel position="stacked">重量 (kg)</IonLabel>
                        <IonInput
                            type="number"
                            value={currentSet.weight}
                            onIonChange={e => {
                                const weight = parseFloat(e.detail.value!);
                                handleSetComplete(currentSet.reps, weight);
                            }}
                        />
                    </IonItem>
                </IonList>

                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 20 }}>
                    <IonButton
                        color="danger"
                        onClick={() => history.push('/workout-plans')}
                    >
                        <IonIcon slot="start" icon={close} />
                        放弃
                    </IonButton>

                    <IonButton
                        color="success"
                        onClick={handleCompleteWorkout}
                        disabled={currentExerciseIndex < workoutRecord.exercises.length - 1 || currentSetIndex < currentExercise.sets.length - 1}
                    >
                        <IonIcon slot="start" icon={checkmark} />
                        完成锻炼
                    </IonButton>
                </div>

                <IonItem style={{ marginTop: 20 }}>
                    <IonLabel position="stacked">锻炼笔记</IonLabel>
                    <IonInput
                        value={notes}
                        onIonChange={e => setNotes(e.detail.value!)}
                        placeholder="记录你的感受..."
                    />
                </IonItem>
            </IonContent>
        </IonPage>
    );
};

export default ActiveWorkoutPage;